using UnityEngine;

namespace Utils.Singleton
{
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _singleton;
        private static readonly object _lock = new object();
        private static bool _applicationIsQuitting = false;

        protected abstract bool NotDestroyed { get; }

        public static T Singleton
        {
            get
            {
                if (_applicationIsQuitting)
                {
                    Debug.LogWarning(
                        $"[MonoSingleton] Instance '{typeof(T)}' already destroyed on application quit. Won't create again - returning null.");
                    return null;
                }

                lock (_lock)
                {
                    if (_singleton == null)
                    {
                        _singleton = FindFirstObjectByType<T>();

                        if (_singleton == null)
                        {
                            GameObject singletonGo = new GameObject($"[{typeof(T).Name}]");
                            _singleton = singletonGo.AddComponent<T>();
                            _singleton.InitializeSingleton();
                            Debug.Log($"[MonoSingleton] An instance of {typeof(T)} was created: {singletonGo.name}");
                        }
                        else
                        {
                            Debug.Log($"[MonoSingleton] Using existing instance: {_singleton.gameObject.name}");
                        }
                    }
                }

                return _singleton;
            }
        }

        private void InitializeSingleton()
        {
            if (NotDestroyed)
            {
                DontDestroyOnLoad(gameObject);
            }
        }

        protected virtual void Awake()
        {
            lock (_lock)
            {
                if (_singleton == null)
                {
                    _singleton = this as T;
                    InitializeSingleton();
                }
                else if (_singleton != this)
                {
                    Debug.LogWarning(
                        $"[MonoSingleton] Another instance of {typeof(T)} already exists ({_singleton.gameObject.name}). Destroying this instance: {gameObject.name}");
                    DestroyImmediate(gameObject);
                }
            }
        }


        protected virtual void OnDestroy()
        {
            lock (_lock)
            {
                if (_singleton == this)
                    _singleton = null;
            }
        }

        protected virtual void OnApplicationQuit()
        {
            _applicationIsQuitting = true;
        }

        protected virtual void OnSingletonInitialized()
        {
        }
    }
}